<template>
  <div class="products-container">
    <!-- 页面标题 -->


    <!-- 过滤器和排序 -->
    <div class="filter-section modern-card slide-up">
      <div class="filter-header">
        <h3 class="filter-title">筛选条件</h3>
        <el-button v-if="isAdmin" type="primary" @click="dialogVisible = true" class="add-product-btn btn-gradient">
          <el-icon>
            <Plus />
          </el-icon>添加商品
        </el-button>
      </div>

      <div class="filter-content">
        <div class="filter-row">
          <div class="filter-label">分类：</div>
          <div class="filter-options">
            <el-radio-group v-model="filterParams.categoryId" @change="() => fetchProducts(true)" class="category-filter">
              <el-radio-button :label="null" class="filter-btn">全部</el-radio-button>
              <el-radio-button v-for="category in categories" :key="category.id" :label="category.id" class="filter-btn">
                {{ category.name }}
              </el-radio-button>
            </el-radio-group>
          </div>
        </div>

        <div class="filter-row">
          <div class="filter-label">价格：</div>
          <div class="filter-options">
            <div class="price-filter">
              <el-slider v-model="priceRange" range :min="0" :max="20000" :step="100" @change="handlePriceChange" class="price-slider" />
              <div class="price-range-display">
                <span class="price-tag">¥{{ priceRange[0] }}</span>
                <span class="price-separator">-</span>
                <span class="price-tag">¥{{ priceRange[1] }}</span>
              </div>
            </div>
          </div>
        </div>

        <div class="filter-row">
          <div class="filter-label">关键词：</div>
          <div class="filter-options">
            <el-input v-model="filterParams.keyword" placeholder="请输入商品名称" @keyup.enter="handleSearch"
              class="search-input modern-input">
              <template #append>
                <el-button @click="handleSearch" class="search-btn">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
          </div>
        </div>
      </div>
    </div>

    <!-- 排序和结果计数 -->
    <div class="results-header">
      <div class="results-count">
        <h2 v-if="props.isHot" class="page-title">热销商品</h2>
        <h2 v-else-if="props.isNew" class="page-title">新品上架</h2>
        <h2 v-else class="page-title">全部商品</h2>
        找到 <span>{{ total }}</span> 个商品
      </div>
      <div class="sorting-options">
        <el-radio-group v-model="filterParams.sort" size="small" @change="fetchProducts">
          <el-radio-button label="default">默认排序</el-radio-button>
          <el-radio-button label="price_asc">价格从低到高</el-radio-button>
          <el-radio-button label="price_desc">价格从高到低</el-radio-button>
          <el-radio-button label="sales_desc">销量优先</el-radio-button>
        </el-radio-group>
      </div>
      <!-- 添加商品按钮 -->
      <el-button v-if="isAdmin" type="primary" @click="dialogVisible = true" class="add-product-btn">
        <el-icon>
          <Plus />
        </el-icon>添加商品
      </el-button>
    </div>

    <!-- 商品列表 -->
    <div class="products-list" v-loading="loading">
      <el-empty v-if="products.length === 0" description="暂无商品" class="empty-state">
        <template #image>
          <div class="empty-image">📦</div>
        </template>
        <template #description>
          <p class="empty-description">暂时没有找到相关商品</p>
        </template>
      </el-empty>
      <div v-else class="products-grid responsive-grid">
        <product-card
          v-for="product in products"
          :key="product.id"
          :product="product"
          @product-deleted="handleProductDeleted"
          class="product-item fade-in"
        />
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-container" v-if="total > 0">
      <el-pagination :current-page="filterParams.page" :page-size="filterParams.size" :page-sizes="[12, 24, 36, 48]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>

    <!-- 添加商品模态框 -->
    <el-dialog v-model="dialogVisible" title="添加商品" width="650px">
      <el-form :model="productForm" :rules="rules" ref="productFormRef" label-width="100px">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="productForm.name" placeholder="请输入商品名称"></el-input>
            </el-form-item>

            <el-form-item label="商品分类" prop="categoryId">
              <el-select v-model="productForm.categoryId" placeholder="请选择商品分类">
                <el-option v-for="item in categories" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="商品价格" prop="price">
              <el-input-number v-model="productForm.price" :precision="2" :step="10" :min="0"></el-input-number>
            </el-form-item>

            <el-form-item label="原价" prop="originalPrice">
              <el-input-number v-model="productForm.originalPrice" :precision="2" :step="10" :min="0"></el-input-number>
            </el-form-item>

            <el-form-item label="库存" prop="stock">
              <el-input-number v-model="productForm.stock" :min="0" :step="1"></el-input-number>
            </el-form-item>

            <el-form-item label="商品属性">
              <el-checkbox v-model="productForm.isHot">热销商品</el-checkbox>
              <el-checkbox v-model="productForm.isNew">新品</el-checkbox>
              <el-checkbox v-model="productForm.isRecommend">推荐商品</el-checkbox>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="商品详情" name="detail">
            <el-form-item label="商品简介" prop="brief">
              <el-input v-model="productForm.brief" type="textarea" :rows="3" placeholder="请输入商品简介"></el-input>
            </el-form-item>

            <el-form-item label="商品详情" prop="detail">
              <el-input v-model="productForm.detail" type="textarea" :rows="6" placeholder="请输入商品详情"></el-input>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="商品图片" name="images">
            <el-form-item label="主图" prop="mainImage">
              <el-input v-model="productForm.mainImage" placeholder="请输入商品主图链接">
                <template #append>
                  <el-button @click="previewMainImage">预览</el-button>
                </template>
              </el-input>
              <div v-if="productForm.mainImage" class="image-preview">
                <img :src="productForm.mainImage" class="preview-image" />
              </div>
            </el-form-item>

            <el-form-item label="详情图片">
              <el-input v-model="detailImageUrl" placeholder="请输入详情图片链接">
                <template #append>
                  <el-button @click="addDetailImage">添加</el-button>
                </template>
              </el-input>

              <div class="detail-images-container">
                <div v-for="(image, index) in detailImages" :key="index" class="detail-image-item">
                  <img :src="image.url" class="detail-image" />
                  <div class="detail-image-actions">
                    <el-button type="danger" size="small" circle @click="removeDetailImage(index)">
                      <el-icon>
                        <Delete />
                      </el-icon>
                    </el-button>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, Delete, Search } from '@element-plus/icons-vue'
import ProductCard from '@/components/ProductCard.vue'
import request from '@/utils/request'

// 移除了防抖函数

// 接收props
const props = defineProps({
  isHot: {
    type: Boolean,
    default: false
  },
  isNew: {
    type: Boolean,
    default: false
  }
})

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const products = ref([])
const total = ref(0)
const categories = ref([])
const brands = ref([])

// 过滤条件
const selectedBrands = ref([])
const priceRange = ref([0, 20000])

// 请求参数
const filterParams = reactive({
  page: 1,
  size: 12,
  categoryId: null,
  brandIds: [],
  minPrice: 0,
  maxPrice: 20000,
  keyword: '',
  sort: 'default',
  isHot: props.isHot ? 1 : null,  // 如果是热销商品页面，设置isHot=1
  isNew: props.isNew ? 1 : null   // 如果是新品页面，设置isNew=1
})

// 判断是否为管理员
const isAdmin = computed(() => {
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  return userInfo.role === 'admin'
})

// 添加商品相关
const dialogVisible = ref(false)
const productFormRef = ref(null)
const activeTab = ref('basic')
const detailImages = ref([])
const detailImageUrl = ref('')

// 商品表单数据
const productForm = reactive({
  name: '',
  categoryId: null,
  brandId: null,
  price: 0,
  originalPrice: 0,
  stock: 0,
  brief: '',
  detail: '',
  mainImage: '',
  isHot: false,
  isNew: false,
  isRecommend: false
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入商品库存', trigger: 'blur' }
  ],
  mainImage: [
    { required: true, message: '请上传商品主图', trigger: 'change' }
  ]
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await request.get('/categories')
    if (res.code === 200) {
      categories.value = res.data && res.data.content ? res.data.content : []
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}


// 获取商品列表
const fetchProducts = async (keepScrollPosition = false) => {
  // 保存当前滚动位置
  const scrollTop = keepScrollPosition ? window.pageYOffset || document.documentElement.scrollTop : 0

  loading.value = true
  try {
    const res = await request.get('/products', { params: filterParams })
    if (res.code === 200) {
      products.value = res.data.content || []
      total.value = res.data.totalElements || 0

      // 如果需要保持滚动位置，在下一帧恢复
      if (keepScrollPosition && scrollTop > 0) {
        setTimeout(() => {
          window.scrollTo(0, scrollTop)
        }, 50)
      }
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}


// 处理搜索
const handleSearch = () => {
  filterParams.page = 1
  // 手动搜索时才同步keyword到URL
  syncFiltersToUrl()
  fetchProducts(true)
}

// 移除了防抖搜索功能，现在只支持按钮搜索和回车搜索

// 处理价格范围变化
const handlePriceChange = () => {
  filterParams.minPrice = priceRange.value[0]
  filterParams.maxPrice = priceRange.value[1]
  filterParams.page = 1
  fetchProducts(true)
}

// 分页处理
const handleSizeChange = (size) => {
  filterParams.size = size
  filterParams.page = 1
  fetchProducts()
}

const handleCurrentChange = (page) => {
  filterParams.page = page
  fetchProducts()
}

// 从URL参数中获取过滤条件
const getFiltersFromUrl = () => {
  if (route.query.category) {
    filterParams.categoryId = parseInt(route.query.category)
  }

  if (route.query.brand) {
    const brandId = parseInt(route.query.brand)
    selectedBrands.value = [brandId]
    filterParams.brandIds = [brandId]
  }

  if (route.query.keyword) {
    filterParams.keyword = route.query.keyword
  }

  // 只有在不是热销商品页面时，才从URL获取isHot参数
  if (route.query.isHot === 'true' && !props.isHot) {
    filterParams.isHot = 1
  }

  // 只有在不是新品页面时，才从URL获取isNew参数
  if (route.query.isNew === 'true' && !props.isNew) {
    filterParams.isNew = 1
  }
}

// 监听路由变化 - 优化以避免不必要的刷新
watch(() => route.query, (newQuery, oldQuery) => {
  // 只有在查询参数真正改变时才重新获取数据
  if (JSON.stringify(newQuery) !== JSON.stringify(oldQuery)) {
    getFiltersFromUrl()
    fetchProducts()
  }
}, { immediate: true })

// 监听 props 变化，当在热销商品和普通商品页面切换时重新加载数据
watch(
  () => [props.isHot, props.isNew],
  () => {
    // 重置过滤参数
    filterParams.isHot = props.isHot ? 1 : null
    filterParams.isNew = props.isNew ? 1 : null
    // 重置页码
    filterParams.page = 1
    // 重新获取商品
    fetchProducts()
    // 滚动到顶部
    window.scrollTo(0, 0)
  }
)

// 将过滤条件同步到URL
const syncFiltersToUrl = () => {
  const query = {}

  if (filterParams.categoryId) {
    query.category = filterParams.categoryId
  }

  if (selectedBrands.value.length === 1) {
    query.brand = selectedBrands.value[0]
  }

  if (filterParams.keyword) {
    query.keyword = filterParams.keyword
  }

  if (filterParams.isHot) {
    query.isHot = 'true'
  }

  if (filterParams.isNew) {
    query.isNew = 'true'
  }

  router.replace({ query })
}

// 监听过滤条件变化，同步到URL（移除keyword监听以防止实时搜索）
watch([
  () => filterParams.categoryId,
  () => selectedBrands.value,
  // 移除 filterParams.keyword 监听，防止输入时实时搜索
  () => filterParams.isHot,
  () => filterParams.isNew
], syncFiltersToUrl, { deep: true })

// 提交表单
const submitForm = async () => {
  if (!productFormRef.value) return

  await productFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 将布尔值转换为数字
        const productData = {
          ...productForm,
          isHot: productForm.isHot ? 1 : 0,
          isNew: productForm.isNew ? 1 : 0,
          isRecommend: productForm.isRecommend ? 1 : 0
        }

        // 提交商品基本信息
        const res = await request.post('/products', productData)

        if (res.code === 200) {
          // 如果有详情图片，提交详情图片
          if (detailImages.value.length > 0) {
            const productId = res.data
            const imageData = detailImages.value.map(img => ({
              productId,
              imageUrl: img.url,
              type: img.type
            }))

            await request.post(`/products/${productId}/images`, imageData)
          }

          ElMessage.success('添加商品成功')
          dialogVisible.value = false
          resetForm()
          fetchProducts() // 刷新商品列表
        } else {
          ElMessage.error(res.message || '添加商品失败')
        }
      } catch (error) {
        console.error('添加商品失败:', error)
        ElMessage.error('添加商品失败')
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (productFormRef.value) {
    productFormRef.value.resetFields()
  }

  // 手动重置其他字段
  productForm.brief = ''
  productForm.detail = ''
  productForm.mainImage = ''
  productForm.isHot = false
  productForm.isNew = false
  productForm.isRecommend = false

  detailImages.value = []
  activeTab.value = 'basic'
  detailImageUrl.value = ''
}

// 预览主图
const previewMainImage = () => {
  if (!productForm.mainImage) {
    ElMessage.warning('请先输入图片链接')
    return
  }
  // 验证链接是否有效
  const img = new Image()
  img.onload = () => {
    ElMessage.success('图片链接有效')
  }
  img.onerror = () => {
    ElMessage.error('图片链接无效，请检查链接是否正确')
  }
  img.src = productForm.mainImage
}

// 添加详情图片
const addDetailImage = () => {
  if (!detailImageUrl.value) {
    ElMessage.warning('请先输入图片链接')
    return
  }

  // 验证链接是否有效
  const img = new Image()
  img.onload = () => {
    detailImages.value.push({
      url: detailImageUrl.value,
      type: 2 // 2表示详情图
    })
    ElMessage.success('已添加详情图片')
    detailImageUrl.value = '' // 清空输入框
  }
  img.onerror = () => {
    ElMessage.error('图片链接无效，请检查链接是否正确')
  }
  img.src = detailImageUrl.value
}

// 移除详情图片
const removeDetailImage = (index) => {
  detailImages.value.splice(index, 1)
  ElMessage.success('已移除详情图片')
}

// 处理商品删除后的刷新逻辑
const handleProductDeleted = () => {
  fetchProducts()
}

onMounted(async () => {
  // 滚动到页面顶部
  window.scrollTo(0, 0)

  // 根据props初始化过滤参数
  filterParams.isHot = props.isHot ? 1 : null
  filterParams.isNew = props.isNew ? 1 : null

  // 从URL获取过滤条件
  getFiltersFromUrl()

  // 获取分类数据
  await fetchCategories()

  // 获取商品数据
  fetchProducts()
})
</script>

<style scoped>
.products-container {
  padding: var(--spacing-xl);
  max-width: 1400px;
  margin: 0 auto;
  background: var(--bg-secondary);
  min-height: 100vh;
}

/* 页面标题 */
.page-header {
  margin-bottom: var(--spacing-xl);
  padding: var(--spacing-xl);
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
  color: white;
  border-radius: var(--radius-xl);
  box-shadow: var(--shadow-xl);
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.title-section h1 {
  font-size: var(--text-4xl);
  font-weight: 700;
  margin: 0 0 var(--spacing-sm);
  color: white;
}

.page-description {
  font-size: var(--text-lg);
  opacity: 0.9;
  margin: 0;
}

/* 过滤器部分 */
.filter-section {
  margin-bottom: var(--spacing-xl);
  padding: var(--spacing-xl);
  background: var(--bg-primary);
  border-radius: var(--radius-xl);
  box-shadow: var(--shadow-md);
  border: 1px solid var(--border-light);
}

.filter-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: var(--spacing-lg);
  padding-bottom: var(--spacing-md);
  border-bottom: 2px solid var(--border-light);
}

.filter-title {
  font-size: var(--text-xl);
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.filter-content {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-lg);
}

.filter-row {
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
}

.filter-label {
  min-width: 80px;
  font-weight: 600;
  color: var(--text-primary);
  font-size: var(--text-base);
}

.filter-options {
  flex: 1;
}

/* 分类过滤器 */
.category-filter .el-radio-button {
  margin-right: var(--spacing-sm);
  margin-bottom: var(--spacing-sm);
}

.filter-btn {
  border-radius: var(--radius-lg) !important;
  border: 2px solid var(--border-light) !important;
  transition: all var(--transition-fast) !important;
}

.filter-btn:hover {
  border-color: var(--primary-color) !important;
  transform: translateY(-2px);
}

/* 价格过滤器 */
.price-filter {
  max-width: 400px;
}

.price-slider {
  margin-bottom: var(--spacing-md);
}

.price-range-display {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--spacing-md);
}

.price-tag {
  background: var(--primary-color);
  color: white;
  padding: 4px 12px;
  border-radius: var(--radius-full);
  font-weight: 600;
  font-size: var(--text-sm);
}

.price-separator {
  color: var(--text-secondary);
  font-weight: 600;
}

/* 搜索输入框 */
.search-input {
  max-width: 300px;
}

.search-btn {
  background: var(--primary-color) !important;
  border-color: var(--primary-color) !important;
  color: white !important;
}

/* 商品列表 */
.products-list {
  margin-bottom: var(--spacing-xl);
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: var(--spacing-xl);
  padding: var(--spacing-lg);
}

.product-item {
  animation-delay: calc(var(--i) * 0.1s);
}

/* 空状态 */
.empty-state {
  padding: var(--spacing-2xl);
  background: var(--bg-primary);
  border-radius: var(--radius-xl);
  box-shadow: var(--shadow-md);
}

.empty-image {
  font-size: 4rem;
  margin-bottom: var(--spacing-lg);
}

.empty-description {
  font-size: var(--text-lg);
  color: var(--text-secondary);
  margin: 0;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding: var(--spacing-xl);
  background: var(--bg-primary);
  border-radius: var(--radius-xl);
  box-shadow: var(--shadow-md);
  margin-top: var(--spacing-xl);
}

/* 添加商品按钮 */
.add-product-btn {
  height: 48px;
  padding: 0 var(--spacing-xl);
  border-radius: var(--radius-lg);
  font-weight: 600;
  box-shadow: var(--shadow-lg);
  transition: all var(--transition-normal);
}

.add-product-btn:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-xl);
}

/* 响应式设计 */
@media (max-width: 1200px) and (min-width: 769px) {
  .products-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .products-container {
    padding: var(--spacing-md);
  }

  .page-header {
    padding: var(--spacing-lg);
  }

  .header-content {
    flex-direction: column;
    gap: var(--spacing-lg);
    text-align: center;
  }

  .filter-section {
    padding: var(--spacing-lg);
  }

  .filter-header {
    flex-direction: column;
    gap: var(--spacing-md);
    align-items: stretch;
  }

  .filter-row {
    flex-direction: column;
    align-items: stretch;
    gap: var(--spacing-sm);
  }

  .filter-label {
    min-width: auto;
  }

  .products-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: var(--spacing-lg);
    padding: var(--spacing-md);
  }
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: relative;
}

.results-count {
  font-size: 14px;
  color: #606266;
}

.results-count span {
  font-weight: bold;
  color: #409EFF;
}

.products-list {
  min-height: 400px;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

.add-product-btn {
  margin-left: 15px;
}

.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.image-uploader:hover {
  border-color: #409EFF;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.preview-image {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.image-preview {
  margin-top: 10px;
  margin-bottom: 10px;
}

.detail-images-container {
  display: flex;
  flex-wrap: wrap;
}

.detail-image-item {
  position: relative;
  margin-right: 10px;
  margin-bottom: 10px;
}

.detail-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
}

.detail-image-actions {
  position: absolute;
  top: 0;
  right: 0;
}

.page-title {
  margin: 0 0 10px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

/* 夜间模式样式 */
html.dark .filter-container {
  background: #2a2a2a !important;
  border-color: #404040 !important;
  color: var(--el-text-color-primary);
}

html.dark .results-header {
  background: #2a2a2a !important;
  border-color: #404040 !important;
  color: var(--el-text-color-primary);
}

html.dark .page-title {
  color: var(--el-text-color-primary) !important;
}

html.dark .results-count {
  color: var(--el-text-color-primary);
}

html.dark .filter-label {
  color: var(--el-text-color-primary);
}

html.dark .filter-row {
  color: var(--el-text-color-primary);
}
</style>